<template>
  <div class="app-container">
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="searchit(2)" :class="{ 'active': selectedStatus === 2 }">已就诊</el-button>
      <el-button type="primary" @click="searchit(1)" :class="{ 'active': selectedStatus === 1 }" >接诊中</el-button>
      <el-button type="primary" @click="searchit(0)" :class="{ 'active': selectedStatus === 0 }">未就诊</el-button>
      <el-button type="primary" @click="turn" >重置</el-button>
    </div>

    <el-form :model="suoyin" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 检索表单 -->
      <el-form-item label="挂号编号" prop="registrationId">
        <el-input
            v-model="suoyin.registrationId"
            placeholder="请输入挂号编号"
            clearable

        />
        <!-- 回车触发查询 -->
      </el-form-item>

      <el-form-item label="患者姓名" prop="realName">
        <el-input
            v-model="suoyin.realName"
            placeholder="请输入患者姓名"
            clearable

        />
        <!-- 回车触发查询 -->
      </el-form-item>

      <el-form-item label="挂号时间" prop="registrationDate">
        <el-date-picker clearable
                        v-model="suoyin.registrationDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择挂号时间"
                        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="挂号状态" prop="receptionStatus" style="height: 30px;width: 175px;border-color: #E7E7E7">
        <el-select v-model="suoyin.receptionStatusName" placeholder="请选择订单状态" clearable>
          <el-option
              v-for="dict in registrationstatus"
              :key="dict.value"
              :value="dict.label"
              @click="choose(dict.value)"
          >
            {{ dict.label }}
          </el-option>
        </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      <el-button type="primary" @click="directtoadd">新增</el-button>
    </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="registrationList" @selection-change="handleSelectionChange">
      <el-table-column label="挂号管理id" align="center" prop="registrationId" />
      <el-table-column label="患者名" align="center" prop="patient.realName" />
      <el-table-column label="性别" align="center" prop="patient.gender" />
      <el-table-column label="年龄" align="center" prop="patient.age" />
      <el-table-column label="手机号" align="center" prop="patient.phoneNumber"/>
      <el-table-column label="医生" align="center" prop="employee1.name" />
      <el-table-column label="科室名" align="center" prop="departments.departmentName" />
      <el-table-column label="挂号时间" align="center" prop="registrationTime" width="180">
        <template #default="scope">
          <span>{{ formatTime(scope.row.registrationTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="挂号日期" align="center" prop="registrationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.registrationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费用" align="center" prop="registrationFee.amount" />
      <el-table-column label="就诊状态" align="center" prop="patient.receptionStatus">
        <template #default="scope">
          <span>
            {{ formatReceptionStatus(scope.row.patient?.receptionStatus) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.patient?.receptionStatus === 2 || scope.row.patient?.receptionStatus == null" link type="primary" icon="Edit" @click="directtoupdate(getIndex(scope.row))" >查看修改</el-button>
          <el-button v-if="scope.row.patient?.receptionStatus === 0" link type="primary" icon="Edit" @click="directtoupdate(getIndex(scope.row))" >编辑</el-button>
          <el-button v-if="scope.row.patient?.receptionStatus === 0" link type="primary" icon="Edit" @click="directtotreatment(scope.row.patient?.patientId)" >接诊</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>

        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />


  </div>
</template>

<script setup name="Registration">
import {
  listRegistration,
  getRegistration,
  delRegistration,
  addRegistration,
  updateRegistration,
  getlistbyIndex
} from "@/api/registration/registration";
import {parseTime} from "@/utils/ruoyi.js";
import moment from 'moment';
import { useRouter } from 'vue-router';  // 导入 useRouter

const router = useRouter();  // 获取路由实例


const { proxy } = getCurrentInstance();

const registrationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
let thelist =ref([]);

//索引
const suoyin = ref({
  pageNum: 1,
  pageSize: 10,
  registrationId:null,
  realName:null,
  registrationDate:null,
  receptionStatus:null,
  receptionStatusName:null
})
function resetsuoyin(){
  suoyin.value = {
    pageNum: 1,
    pageSize: 10,
    registrationId: null,
    realName: null,
    registrationDate: null,
    receptionStatus: null,
    receptionStatusName: null
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    registrationId: null,
    patient: {
      patientId:null,
      realName:null,
    },
    departments: null,
    employee1:null,
    employee2:null,
    registrationFee:null,
    registrationTime: null,
    registrationDate: null,
    registrationFeeName: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);



/** 查询挂号管理列表 */
function getList() {

  loading.value = true;
  listRegistration(queryParams.value).then(response => {
    registrationList.value = response.rows;
    total.value = response.total;
    console.log("registrationList")
    console.log(registrationList.value)
    console.log(response)
    loading.value = false;
    thelist.value = response.rows
    // console.log( "registrationList ")
    // console.log(registrationList.value[0])
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    registrationId: null,
    patient: {
      patientId:null,
      realName:null,
    },
    departments: null,
    employee1:null,
    employee2:null,
    registrationFee:null,
    registrationTime: null,
    registrationDate: null,
    registrationFeeName: null,
  };
  proxy.resetForm("registrationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(suoyin.value)
  loading.value = true;
  getlistbyIndex(suoyin.value).then(response => {
    registrationList.value = response.rows;
    total.value = response.total;
    console.log("getlistbyIndex")
    console.log(registrationList.value)
    console.log(response)
    loading.value = false;
  });
}

function searchit(num){
  selectedStatus.value = num; // 点击时更新当前选中的按钮状态
  resetsuoyin()
  suoyin.value.receptionStatus = num;
  getlistbyIndex(suoyin.value).then(response => {
    registrationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.registrationId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加挂号管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _registrationId = row.registrationId || ids.value
  getRegistration(_registrationId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改挂号管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["registrationRef"].validate(valid => {
    if (valid) {
      if (form.value.registrationId != null) {
        updateRegistration(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRegistration(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _registrationIds = row.registrationId || ids.value;
  proxy.$modal.confirm('是否确认删除挂号管理编号为"' + _registrationIds + '"的数据项？').then(function() {
    return delRegistration(_registrationIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('registration/registration/export', {
    ...queryParams.value
  }, `registration_${new Date().getTime()}.xlsx`)
}

 function  formatTime(time) {
   if (!time) return '';  // 如果没有时间，返回空字符串
   return moment(time, 'HH:mm:ss').format('HH:mm:ss');  // 直接格式化为 HH:mm:ss/
  }
function formatReceptionStatus(status) {
    if (status === null || status === undefined) {
      return '';  // 如果没有值或值为 null，返回空字符串
    }
    if (status === 0) {
      return '未就诊';
    } else if (status === 1) {
      return '接诊中';
    } else if (status === 2) {
      return '已就诊';
    }
    return '';  // 如果 status 不在 0, 1, 2 之间，返回空字符串

}
const registrationstatus = [
  {label:"未就诊" , value:"0"},
  {label:"接诊中" , value:"1"},
  {label:"已就诊" , value:"2"}
]
function choose(value)  {
  suoyin.value.receptionStatus = value;
}
function directtoadd() {
  router.push({ path: '/system/registration/view/addregistration' });
}

getList();

function directtoupdate(scope) {
  console.log(scope)
  console.log(registrationList.value[scope])
  let alldata = ref(
      registrationList.value[scope]
  )
  console.log("directtoupdate")
  console.log(alldata.value)
  router.push({ path: '/system/registration/view/addregistration',  query: { alldata: JSON.stringify(alldata.value)}
  }) // 传递数据作为查询参数 })
}

function getIndex(row) {
  return registrationList.value.findIndex(item => item.registrationId === row.registrationId);
}


const selectedStatus = ref(null); // 默认没有选中任何按钮

function turn(){
  selectedStatus.value = null
  getList();
}
function directtotreatment(num){
  router.push({ path: '/snrecord' , query: { num }  })
}


</script>
<style scoped>
.active {
  background-color: white; /* 激活按钮的背景色 */
  color: black; /* 激活按钮的文字颜色 */
}
</style>
